//
//  M_CatalogVC.swift
//  letuofu
//
//  Created by WH-JS on 2019/12/13.
//  Copyright © 2019 WH-JS. All rights reserved.
//

import UIKit

class M_CatalogVC: BaseViewControllerWithHeader,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {

    enum CatalogType:Int {
        case CatalogZY = 105001
        case CatalogJD = 105002
    }
    
    //自营目录
    let tableZYView = QuickTableView<[String:Any?],M_CatalogCell>()
    var colltionZYView : UICollectionView?
    var dataZYArr = [[String:Any?]]()
    var dataZYMainArr = [[String:Any?]]()
    var dataZYSubArr = [[String:Any?]]()
    var dataZYDetailArr = [[[String:Any?]]]()
    
    //京东目录
    let tableJDView = QuickTableView<[String:Any?],M_CatalogCell>()
    var colltionJDView : UICollectionView?
    var dataJDArr = [[String:Any?]]()
    var dataJDMainArr = [[String:Any?]]()
    var dataJDSubArr = [[String:Any?]]()
    var dataJDDetailArr = [[[String:Any?]]]()
    
    //当前选中二级目录
    var curData = [String:Any?]()
    //头部导航
    let tabHeader = SlidingTabHeaderView(screenWidth:375.0, height: 43.0,titles:["自营专区","京东配送专区"],titleSpace:100)

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
//        getZYCatalogList(page: 1, pageSize: 1000)
        let name1 = NSNotification.Name(rawValue:MALL_CHANGE)
        NotificationCenter.default.addObserver(self, selector: #selector(notfifica(sender:)), name: name1, object: nil)
    }

    override func viewWillAppear(_ animated: Bool) {
        if dataJDArr.count == 0 {
            getJDCatalogList(page: 1, pageSize: 1000)
        }
        
        if dataZYArr.count == 0 {
            getZYCatalogList(page: 1, pageSize: 1000)
        }
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

    func getZYCatalogList(page: Int, pageSize:Int) {
        self.dataZYArr = []
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? ""]
        API.request(url: .M_ZYCatalog, params: params) { (result) in
            if result.success {
               if let dl = result.data?.getDictionary("data") {
                   for item in dl.getDictList("items") ?? [] {
                       self.dataZYArr.append(item)
                   }
               }
            }else{
                self.dataZYArr = []
            }
            self.queryZYData()
        }
    }
    
    func getJDCatalogList(page: Int, pageSize:Int) {
        self.dataJDArr = []
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? ""]
        API.request(url: .M_JDCatalog, params: params) { (result) in
            if result.success {
               if let dl = result.data?.getDictionary("data") {
                   for item in dl.getDictList("items") ?? [] {
                       self.dataJDArr.append(item)
                   }
               }
            }else{
                self.dataJDArr = []
            }
            self.queryJDData()
        }
    }
}

// MARK: UI
extension M_CatalogVC {
    func setupUI() {
        headView.drawImage(named: "lepaidui_2") { (make) in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(backButton.snp.centerY)
        }
        backButton.isHidden = true
        
//        drawRightButton(imageName: "xiaoxi_4")
//        .addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        let newsButton = drawRightButton(imageName: "xiaoxi_4")
        newsButton.addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        UnreadPointForNewsButton(button: newsButton, pointRadius: 3.5,
                                 pointOffset: .init(x: -9.5, y: 10),  color: .xE0551B)

        safeView.addSubview(tabHeader)
        tabHeader.snp.makeConstraints { (make) in
            make.top.equalTo(headView.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(43.0)
        }
        //画横线
        let line = tabHeader.drawView { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(1)
            make.height.equalTo(2)
        }
        line.backgroundColor = .xF2F2F2
        
        let scrollView = SlidingTabScrollView(screenWidth: 375, tabCount: 2)
        safeView.addSubview(scrollView)
        scrollView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(tabHeader.snp.bottom)
        }
        if let pnpNavCtrl = (self.navigationController ?? self.tabBarController?.navigationController) as? PushAndPopNavigationController {
            scrollView.panGestureRecognizer.require(toFail: pnpNavCtrl.leftPan)
        }
        
        scrollView.tabHeader = tabHeader
        scrollView.isScrollEnabled = false
        tabHeader.scrollView = scrollView
        setupZYUI(contentView: scrollView.pages[0])
        setupJDUI(contentView: scrollView.pages[1])
    }
    
    func setupZYUI(contentView:UIView) {
        //添加列表
        contentView.addSubview(tableZYView)
        tableZYView.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.top.equalToSuperview()
            make.bottom.equalToSuperview()
            make.width.equalTo(90)
        }
        tableZYView.backgroundColor = .xF7F7F7
                        
        //当点击表格行时
        tableZYView.onDataSelectedSubject().bindWeak(self) { (data, s) in
            s.onSelectZYCell(data: data)
        }
        
        //刷新相关事件绑定
        tableZYView.onSetCellSubject().bindWeak(self) { (cell, s) in
        }
    
        let layout = UICollectionViewFlowLayout()
        layout.sectionInset = .init(top: 10, left: 15, bottom: 10, right: 15)
        colltionZYView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        colltionZYView?.tag = CatalogType.CatalogZY.rawValue
        //注册一个cell
        colltionZYView!.register(M_CatalogSubCell.self, forCellWithReuseIdentifier:"cell")
        //注册一个head
        colltionZYView!.register(M_CatalogSubHead.self, forSupplementaryViewOfKind:UICollectionView.elementKindSectionHeader, withReuseIdentifier: "header")
        colltionZYView?.delegate = self;
        colltionZYView?.dataSource = self;
        colltionZYView?.backgroundColor = .white
        //设置每一个cell的宽高
        layout.itemSize = CGSize(width: 70, height: 100)
        contentView.addSubview(colltionZYView!)
        colltionZYView?.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.left.equalTo(tableZYView.snp.right)
            make.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
    }
    
    func setupJDUI(contentView:UIView) {
        //添加列表
        contentView.addSubview(tableJDView)
        tableJDView.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.top.equalToSuperview()
            make.bottom.equalToSuperview()
            make.width.equalTo(90)
        }
        tableJDView.backgroundColor = .xF7F7F7
                        
        //当点击表格行时
        tableJDView.onDataSelectedSubject().bindWeak(self) { (data, s) in
            s.onSelectJDCell(data: data)
        }
        
        //刷新相关事件绑定
        tableJDView.onSetCellSubject().bindWeak(self) { (cell, s) in
        }
        
        let layout = UICollectionViewFlowLayout()
        layout.sectionInset = .init(top: 20, left: 15, bottom: 0, right: 15)
        colltionJDView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        colltionJDView?.tag = CatalogType.CatalogJD.rawValue
        //注册一个cell
        colltionJDView!.register(M_CatalogSubCell_Lab.self, forCellWithReuseIdentifier:"cell")
        //注册一个head
        colltionJDView!.register(M_CatalogSubHead.self, forSupplementaryViewOfKind:UICollectionView.elementKindSectionHeader, withReuseIdentifier: "header")
        colltionJDView?.delegate = self;
        colltionJDView?.dataSource = self;
        colltionJDView?.backgroundColor = .white
        //设置每一个cell的宽高
        layout.itemSize = CGSize(width: 70, height: 50)
        contentView.addSubview(colltionJDView!)
        colltionJDView?.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.left.equalTo(tableJDView.snp.right)
            make.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
    }
}


// MARK: event & action
extension M_CatalogVC {
    @objc func _xiaoxiButtonClick(button: Button) {
        let vc = M_NewsListVC()
        pushViewController(vc)
    }
    
    @objc func notfifica(sender:NSNotification) {
        dataZYArr.removeAll()
        dataJDArr.removeAll()
        getJDCatalogList(page: 1, pageSize: 1000)
        getZYCatalogList(page: 1, pageSize: 1000)
    }
    
    func queryZYData() {
        dataZYMainArr = dataZYArr.filter({$0.getString("pCataID") == "0"})
        tableZYView.list = dataZYMainArr
        tableZYView.reloadData()
        if dataZYMainArr.count > 0 {
            tableZYView.selectRow(at: .init(row: 0, section: 0), animated: false, scrollPosition: .none)
            self.onSelectZYCell(data: dataZYMainArr[0])
        }
    }
    
    func queryZYSubData() {
        colltionZYView?.reloadData()
    }
    
    //当点击表格行事件
    func onSelectZYCell(data:[String:Any?]){
        dataZYSubArr = dataZYArr.filter({$0.getString("pCataID") == data.getString("cataID")})
        dataZYDetailArr.removeAll()
        for subdic in dataZYSubArr {
            let ary = dataZYArr.filter({$0.getString("pCataID") == subdic.getString("cataID")})
            dataZYDetailArr.append(ary)
        }
        colltionZYView?.reloadData()
    }
    
    
    
    func queryJDData() {
        dataJDMainArr = dataJDArr.filter({$0.getString("pCataID") == "0"})
        tableJDView.list = dataJDMainArr
        tableJDView.reloadData()
        if dataJDMainArr.count > 0 {
            tableJDView.selectRow(at: .init(row: 0, section: 0), animated: false, scrollPosition: .none)
            self.onSelectJDCell(data: dataJDMainArr[0])
        }
    }
    
    func queryJDSubData() {
        colltionJDView?.reloadData()
    }
    
    //当点击表格行事件
    func onSelectJDCell(data:[String:Any?]){
        dataJDSubArr = dataJDArr.filter({$0.getString("pCataID") == data.getString("cataID")})
        dataJDDetailArr.removeAll()
        for subdic in dataJDSubArr {
            let ary = dataJDArr.filter({$0.getString("pCataID") == subdic.getString("cataID")})
            dataJDDetailArr.append(ary)
        }
        colltionJDView?.reloadData()
    }
    
    ///collectionViewDelegate
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let zoneCode = LocalStorage.getAryToZone(forKey: ZoneCode105)
        var ary = [[String:Any?]]()
        switch collectionView.tag {
        case CatalogType.CatalogZY.rawValue:
            ary = dataZYDetailArr[indexPath.section]
            let vc = M_ProductByCategoryVC(dataSubArr: ary, curDicIndex: indexPath.row,zoneCode: zoneCode![0])
            pushViewController(vc)
            curData = dataZYSubArr[indexPath.section]
            vc.headTitle.text = curData.getString("cataName")
        case CatalogType.CatalogJD.rawValue:
            ary = dataJDDetailArr[indexPath.section]
            let vc = M_ProductByCategoryVC(dataSubArr: ary, curDicIndex: indexPath.row,zoneCode: zoneCode![1])
            pushViewController(vc)
            curData = dataJDSubArr[indexPath.section]
            vc.headTitle.text = curData.getString("cataName")
        default:
            break
        }
    }
    
    //返回多少个组
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        switch collectionView.tag {
        case CatalogType.CatalogZY.rawValue:
            return dataZYSubArr.count
        case CatalogType.CatalogJD.rawValue:
            return dataJDSubArr.count
        default:
            return dataZYSubArr.count
        }
    }
    
    //返回多少个cell
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        switch collectionView.tag {
        case CatalogType.CatalogZY.rawValue:
            return dataZYDetailArr[section].count
        case CatalogType.CatalogJD.rawValue:
            return dataJDDetailArr[section].count
        default:
            return dataZYDetailArr[section].count
        }
    }
    
    //构建每个cell
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        switch collectionView.tag {
        case CatalogType.CatalogZY.rawValue:
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! M_CatalogSubCell
            let dic = dataZYDetailArr[indexPath.section][indexPath.row]
            cell.celldata = dic
            return cell
        case CatalogType.CatalogJD.rawValue:
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! M_CatalogSubCell_Lab
            let dic = dataJDDetailArr[indexPath.section][indexPath.row]
            cell.celldata = dic
            return cell
        default:
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! M_CatalogSubCell
            return cell
        }
    }
    
    //返回HeadView的宽高
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
            return CGSize(width: collectionView.bounds.width, height: 53)
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        var dic = [String:Any?]()
        switch collectionView.tag {
        case CatalogType.CatalogZY.rawValue:
            dic = dataZYSubArr[indexPath.section]
            break
        case CatalogType.CatalogJD.rawValue:
            dic = dataJDSubArr[indexPath.section]
        default:
            break
        }
        
        var v = M_CatalogSubHead()
        if kind == UICollectionView.elementKindSectionHeader{
            v = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "header", for: indexPath) as! M_CatalogSubHead
            v.title = dic.getString("cataName") ?? "未知分类"
        }
        return v
    }
}
